import React, { useRef } from 'react'
import { useAntdTable } from 'ahooks'
import { Form, Input, Button, Table, Space, Modal, message } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { formatDate } from '@/utils'
import { deleteRole, getRoleList } from '@/api/roles'
import SearchForm from '@/components/SearchForm'
import CreateDept from './components/CreateRole'
import type { ColumnsType } from 'antd/es/table'
import SetPermission from './components//SetPermission'
import { ModelAction } from '@/types/modal'
import { IGetRoleListParams, IRoleItem } from '@/types/roles'
import AuthButton from '@/components/AuthButton'

const RoleList: React.FC = () => {
  const [form] = Form.useForm()
  const createRef = useRef<{ open: (type: ModelAction, data?: IRoleItem) => void }>()
  const setPermissionRef = useRef<{ open: (type: ModelAction, data?: IRoleItem) => void }>()

  const getTableData = ({ current, pageSize }: { current: number; pageSize: number }, formData: IGetRoleListParams) => {
    return getRoleList({
      ...formData,
      pageNum: current,
      pageSize
    }).then(res => {
      return {
        total: res.data.page.total,
        list: res.data.list
      }
    })
  }
  const { tableProps, search } = useAntdTable(getTableData, { form })

  // 条件搜索
  const handleSearch = () => {
    search.submit()
  }

  // 重置
  const handleReset = () => {
    search.reset()
  }
  // 新增
  const handleAdd = () => {
    createRef.current?.open('create')
  }
  // 设置权限
  const handleSetPermission = (record: IRoleItem) => {
    setPermissionRef.current?.open('create', record)
  }
  // 编辑
  const handleEdit = (record: IRoleItem) => {
    createRef.current?.open('edit', record)
  }
  // 删除
  const handleDel = (id: string) => {
    Modal.confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: <span>确定删除吗？</span>,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        handleDelRole(id)
      }
    })
  }

  const handleDelRole = (id: string) => {
    deleteRole(id).then(() => {
      message.success('删除成功')
      search.reset()
    })
  }
  const columns: ColumnsType<IRoleItem> = [
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName'
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark'
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      render(time: string) {
        return formatDate(time)
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render(time: string) {
        return formatDate(time)
      }
    },
    {
      title: '操作',
      key: 'address',
      render(record) {
        return (
          <Space>
            <AuthButton type='text' onClick={() => handleEdit(record)} auth='role@edit'>
              编辑
            </AuthButton>
            <AuthButton
              type='text'
              onClick={() => {
                handleSetPermission(record)
              }}
              auth='role@setting'
            >
              设置权限
            </AuthButton>
            <AuthButton type='text' danger onClick={() => handleDel(record._id)} auth='role@delete'>
              删除
            </AuthButton>
          </Space>
        )
      }
    }
  ]
  return (
    <div className='list_page'>
      <div className='list_page__header'>
        <SearchForm form={form} onSubmit={handleSearch} onReset={handleReset}>
          <Form.Item label='角色名称' name='roleName'>
            <Input />
          </Form.Item>
        </SearchForm>
      </div>
      <div className='list_page__wrapper'>
        <div className='list_page__wrapper__toolbar'>
          <div className='list_page__wrapper__toolbar__title'>角色列表</div>
          <div className='list_page__wrapper__toolbar__right'>
            <AuthButton type='primary' style={{ marginRight: 8 }} onClick={handleAdd} auth="role@create">
              新增
            </AuthButton>
          </div>
        </div>
        <div>
          <Table columns={columns} rowKey='_id' {...tableProps}></Table>
        </div>
      </div>
      <CreateDept
        mRef={createRef}
        update={() => {
          search.submit()
        }}
      />
      <SetPermission
        mRef={setPermissionRef}
        update={() => {
          search.submit()
        }}
      />
    </div>
  )
}

export default RoleList
